package com.cmcc.driver.ui.main

import android.os.Bundle
import android.speech.tts.TextToSpeech
import android.text.TextUtils
import android.util.Log
import android.view.Window
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.alibaba.android.arouter.facade.annotation.Route
import com.amap.api.navi.AMapNavi
import com.amap.api.navi.AMapNaviListener
import com.amap.api.navi.AMapNaviView
import com.amap.api.navi.AMapNaviViewListener
import com.amap.api.navi.enums.NaviType
import com.amap.api.navi.model.*
import com.autonavi.tbt.TrafficFacilityInfo
import com.cmcc.driver.R
import com.cmcc.driver.config.DriverPath
import com.cmcc.shared.BaseActivity
import com.cmcc.shared.utils.L
import com.google.android.gms.maps.model.LatLng
import java.util.*


@Route(path = DriverPath.NAVIGATION)
class DriverNavigationActivity : AppCompatActivity(), AMapNaviListener, AMapNaviViewListener,
    TextToSpeech.OnInitListener {

    private val HKG = "HKG"
    private val YUE = "yue"
    private var mAMapNaviView: AMapNaviView? = null
    private var mAMapNavi: AMapNavi? = null
    private val sList: MutableList<NaviLatLng> = ArrayList()
    private val eList: MutableList<NaviLatLng> = ArrayList()
    private var mWayPointList: List<NaviLatLng> = ArrayList()
    private var mTextToSpeech: TextToSpeech? = null



    /***获取TAG的activity名称 */
    protected val TAG = this.javaClass.simpleName;
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        Log.e(TAG, "当前所在Activity: "+TAG)
        requestWindowFeature(Window.FEATURE_NO_TITLE)

        mTextToSpeech = TextToSpeech(this, this)
        // 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
        mTextToSpeech?.setPitch(1.2f)
        // 设置语速
        mTextToSpeech?.setSpeechRate(0.9f)

        mAMapNavi = AMapNavi.getInstance(this)
        mAMapNavi?.addAMapNaviListener(this)
        mAMapNavi?.setUseInnerVoice(false)


        //设置模拟导航的行车速度
        mAMapNavi?.setEmulatorNaviSpeed(75)
        val startLatlng = intent.getParcelableExtra<LatLng>("start_point")
        val endLatLng = intent.getParcelableExtra<LatLng>("end_point")
        sList.add(NaviLatLng(startLatlng.latitude, startLatlng.longitude))
        eList.add(NaviLatLng(endLatLng.latitude, endLatLng.longitude))

        setContentView(R.layout.activity_driver_navigation)

        mAMapNaviView = findViewById(R.id.navi_view)
        mAMapNaviView?.onCreate(savedInstanceState)
        mAMapNaviView?.setAMapNaviViewListener(this)
    }


    override fun onResume() {
        super.onResume()
        mAMapNaviView!!.onResume()
    }

    override fun onPause() {
        super.onPause()
        mAMapNaviView!!.onPause()
    }

    override fun onDestroy() {
        super.onDestroy()
        mAMapNaviView!!.onDestroy()
        //since 1.6.0 不再在naviview destroy的时候自动执行AMapNavi.stopNavi();请自行执行
        mAMapNavi?.stopNavi()
        mAMapNavi?.destroy()

        if (mTextToSpeech != null) {
            // 不管是否正在朗读TTS都被打断
            mTextToSpeech?.stop()
            // 关闭，释放资源
            mTextToSpeech?.shutdown()
            mTextToSpeech = null
        }
    }

    override fun onInitNaviFailure() {
        Toast.makeText(this, "init navi Failed", Toast.LENGTH_SHORT).show()
    }

    override fun onInitNaviSuccess() {
        //初始化成功
        /**
         * 方法: int strategy=mAMapNavi.strategyConvert(congestion, avoidhightspeed, cost, hightspeed, multipleroute); 参数:
         *
         * @congestion 躲避拥堵
         * @avoidhightspeed 不走高速
         * @cost 避免收费
         * @hightspeed 高速优先
         * @multipleroute 多路径
         *
         *  说明: 以上参数都是boolean类型，其中multipleroute参数表示是否多条路线，如果为true则此策略会算出多条路线。
         *  注意: 不走高速与高速优先不能同时为true 高速优先与避免收费不能同时为true
         */
        var strategy: Int? = 0
        try {
            //再次强调，最后一个参数为true时代表多路径，否则代表单路径
            strategy = mAMapNavi?.strategyConvert(true, false, false, false, false)
        } catch (e: Exception) {
            e.printStackTrace()
        }

//        mAMapNavi?.setCarNumber("京", "DFZ588")
        mAMapNavi?.calculateDriveRoute(sList, eList, mWayPointList, strategy ?: 0)
    }

    override fun onStartNavi(type: Int) {
        //开始导航回调
    }

    override fun onTrafficStatusUpdate() {
        //
    }

    override fun onLocationChange(location: AMapNaviLocation) {
        //当前位置回调
    }

    /**
     * 导航 SDK 中透传文字的回调方法见下表。
     */
    override fun onGetNavigationText(type: Int, text: String) {
        L.e("onGetNavigationText:"+text)
        //播报类型和播报文字回调
        if (mTextToSpeech != null && !TextUtils.isEmpty(text)) {
            /*
                TextToSpeech的speak方法有两个重载。
                // 执行朗读的方法
                speak(CharSequence text,int queueMode,Bundle params,String utteranceId);
                // 将朗读的的声音记录成音频文件
                synthesizeToFile(CharSequence text,Bundle params,File file,String utteranceId);
                第二个参数queueMode用于指定发音队列模式，两种模式选择
                （1）TextToSpeech.QUEUE_FLUSH：该模式下在有新任务时候会清除当前语音任务，执行新的语音任务
                （2）TextToSpeech.QUEUE_ADD：该模式下会把新的语音任务放到语音任务之后，
                等前面的语音任务执行完了才会执行新的语音任务
             */
            mTextToSpeech?.speak(text, TextToSpeech.QUEUE_ADD, null);
        }
    }

    override fun onGetNavigationText(s: String) {

    }

    override fun onEndEmulatorNavi() {
        //结束模拟导航
    }

    override fun onArriveDestination() {
        //到达目的地
    }

    override fun onCalculateRouteFailure(errorInfo: Int) {
        //路线计算失败
        Log.e("dm", "--------------------------------------------")
        Log.i(
            "dm",
            "错误码详细$errorInfo 链接见：http://lbs.amap.com/api/android-navi-sdk/guide/tools/errorcode/"
        )
        Log.e("dm", "--------------------------------------------")
    }

    override fun onReCalculateRouteForYaw() {
        //偏航后重新计算路线回调
    }

    override fun onReCalculateRouteForTrafficJam() {
        //拥堵后重新计算路线回调
    }

    override fun onArrivedWayPoint(wayID: Int) {
        //到达途径点
    }

    override fun onGpsOpenStatus(enabled: Boolean) {
        //GPS开关状态回调
    }

    override fun onNaviSetting() {
        //底部导航设置点击回调
    }

    override fun onNaviMapMode(naviMode: Int) {
        //导航态车头模式，0:车头朝上状态；1:正北朝上模式。
    }

    override fun onNaviCancel() {
        finish()
    }


    override fun onNaviTurnClick() {
        //转弯view的点击回调
    }

    override fun onNextRoadClick() {
        //下一个道路View点击回调
    }


    override fun onScanViewButtonClick() {
        //全览按钮点击回调
    }

    @Deprecated("")
    override fun onNaviInfoUpdated(naviInfo: AMapNaviInfo) {
        //过时
    }

    override fun updateCameraInfo(aMapCameraInfos: Array<AMapNaviCameraInfo>) {

    }

    override fun onServiceAreaUpdate(amapServiceAreaInfos: Array<AMapServiceAreaInfo>) {

    }

    override fun onNaviInfoUpdate(naviinfo: NaviInfo) {
        //导航过程中的信息更新，请看NaviInfo的具体说明
    }

    override fun OnUpdateTrafficFacility(trafficFacilityInfo: TrafficFacilityInfo) {
        //已过时
    }

    override fun OnUpdateTrafficFacility(aMapNaviTrafficFacilityInfo: AMapNaviTrafficFacilityInfo) {
        //已过时
    }

    override fun showCross(aMapNaviCross: AMapNaviCross) {
        //显示转弯回调
    }

    override fun hideCross() {
        //隐藏转弯回调
    }

    override fun showLaneInfo(
        laneInfos: Array<AMapLaneInfo>,
        laneBackgroundInfo: ByteArray,
        laneRecommendedInfo: ByteArray
    ) {
        //显示车道信息

    }

    override fun hideLaneInfo() {
        //隐藏车道信息
    }

    override fun onCalculateRouteSuccess(ints: IntArray) {
        //多路径算路成功回调
        mAMapNavi?.startNavi(NaviType.GPS)
    }

    override fun notifyParallelRoad(i: Int) {
        if (i == 0) {
//            Toast.makeText(this, "当前在主辅路过渡", Toast.LENGTH_SHORT).show()
            Log.d("wlx", "当前在主辅路过渡")
            return
        }
        if (i == 1) {
//            Toast.makeText(this, "当前在主路", Toast.LENGTH_SHORT).show()

            Log.d("wlx", "当前在主路")
            return
        }
        if (i == 2) {
//            Toast.makeText(this, "当前在辅路", Toast.LENGTH_SHORT).show()

            Log.d("wlx", "当前在辅路")
        }
    }

    override fun OnUpdateTrafficFacility(aMapNaviTrafficFacilityInfos: Array<AMapNaviTrafficFacilityInfo>) {
        //更新交通设施信息
    }

    override fun updateAimlessModeStatistics(aimLessModeStat: AimLessModeStat) {
        //更新巡航模式的统计信息
    }


    override fun updateAimlessModeCongestionInfo(aimLessModeCongestionInfo: AimLessModeCongestionInfo) {
        //更新巡航模式的拥堵信息
    }

    override fun onPlayRing(i: Int) {

    }


    override fun onLockMap(isLock: Boolean) {
        //锁地图状态发生变化时回调
    }

    override fun onNaviViewLoaded() {
        Log.d("wlx", "导航页面加载成功")
        Log.d("wlx", "请不要使用AMapNaviView.getMap().setOnMapLoadedListener();会overwrite导航SDK内部画线逻辑")
    }

    override fun onMapTypeChanged(i: Int) {

    }

    override fun onNaviViewShowMode(i: Int) {

    }

    override fun onNaviBackClick(): Boolean {
        return false
    }


    override fun showModeCross(aMapModelCross: AMapModelCross) {

    }

    override fun hideModeCross() {

    }

    override fun updateIntervalCameraInfo(
        aMapNaviCameraInfo: AMapNaviCameraInfo,
        aMapNaviCameraInfo1: AMapNaviCameraInfo,
        i: Int
    ) {

    }

    override fun showLaneInfo(aMapLaneInfo: AMapLaneInfo) {

    }

    override fun onCalculateRouteSuccess(aMapCalcRouteResult: AMapCalcRouteResult) {

    }

    override fun onCalculateRouteFailure(aMapCalcRouteResult: AMapCalcRouteResult) {

    }

    override fun onNaviRouteNotify(aMapNaviRouteNotifyData: AMapNaviRouteNotifyData) {

    }

    override fun onInit(status: Int) {
        if (status === TextToSpeech.SUCCESS) { /*
                使用的是小米手机进行测试，打开设置，在系统和设备列表项中找到更多设置，
            点击进入更多设置，在点击进入语言和输入法，见语言项列表，点击文字转语音（TTS）输出，
            首选引擎项有三项为Pico TTs，科大讯飞语音引擎3.0，度秘语音引擎3.0。其中Pico TTS不支持
            中文语言状态。其他两项支持中文。选择科大讯飞语音引擎3.0。进行测试。

                如果自己的测试机里面没有可以读取中文的引擎，
            那么不要紧，我在该Module包中放了一个科大讯飞语音引擎3.0.apk，将该引擎进行安装后，进入到
            系统设置中，找到文字转语音（TTS）输出，将引擎修改为科大讯飞语音引擎3.0即可。重新启动测试
            Demo即可体验到文字转中文语言。
             */
// setLanguage设置语言
            val result = mTextToSpeech!!.setLanguage(Locale(YUE, HKG))
            // TextToSpeech.LANG_MISSING_DATA：表示语言的数据丢失
// TextToSpeech.LANG_NOT_SUPPORTED：不支持
            if (result == TextToSpeech.LANG_MISSING_DATA
                || result == TextToSpeech.LANG_NOT_SUPPORTED
            ) {
//                Toast.makeText(this, "数据丢失或不支持", Toast.LENGTH_SHORT).show()
            }
        }
    }
}